﻿using System;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;

namespace FileClient
{
    public partial class Splash : Form
    {
        int NumberOfTrys = 1;
        private bool mouseIsDown = false;
        private System.Drawing.Point firstPoint;

        public Splash(Form parentObj)
        {
            InitializeComponent();            
            new Thread(ServerUp).Start();
        }

        private void ServerUp()
        {
            if (ItsUp()) Hide();
            else ServerUp();
        }

        private Boolean ItsUp()
        {
            using (TcpClient tcp = new TcpClient())
            {
                IAsyncResult ar = tcp.BeginConnect(Config.ipaddress[Config.IP], 5331, null, null);
                System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
                    {
                        Loading.Text = "Unable To Connect Retry " + NumberOfTrys++;
                        return false;
                    }
                    tcp.EndConnect(ar);
                }
                catch { Loading.Text = "Unable To Connect Retry " + NumberOfTrys++; ServerUp(); }
                wh.Close();
                Loading.Text = "Connected To: " + tcp.Client.RemoteEndPoint;
                tcp.Close();
                Thread.Sleep(1000);
                return true;
            }
        }

        private void _MouseDown(object sender, MouseEventArgs e)
        { firstPoint = e.Location; mouseIsDown = true; }

        private void _MouseUp(object sender, MouseEventArgs e)
        { mouseIsDown = false; }

        private void _MouseMove(object sender, MouseEventArgs e)
        {
            if (mouseIsDown)
            {
                // Get the difference between the two points
                int xDiff = firstPoint.X - e.Location.X;
                int yDiff = firstPoint.Y - e.Location.Y;

                // Set the new point
                int x = this.Location.X - xDiff;
                int y = this.Location.Y - yDiff;
                this.Location = new System.Drawing.Point(x, y);
            }
        }

        private void Splash_FormClosing(object sender, FormClosingEventArgs e)
        {
            Environment.Exit(-1);
        }
    }
}
